#include "stdafx.h"
#include "DebugFile.h"

CDebugFile::CDebugFile(LPCTSTR lpszFileName)
{
    m_hFile = ::CreateFile(lpszFileName, 
        GENERIC_WRITE|GENERIC_READ, 
        FILE_SHARE_READ,
        NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (m_hFile==INVALID_HANDLE_VALUE) return;
    InitializeCriticalSection(&m_CriticalSection);
    WORD wUniCode= 0xfeff;
    DWORD dw;
    WriteFile(m_hFile, &wUniCode, 2, &dw, 0);
}

CDebugFile::~CDebugFile()
{
    ::FlushFileBuffers(m_hFile);
    ::CloseHandle(m_hFile);
    DeleteCriticalSection(&m_CriticalSection);
}

void CDebugFile::WriteLog(LPCTSTR lpszFormat, ...)
{
	EnterCriticalSection(&m_CriticalSection);
    TCHAR szMsg[1024];
    DWORD dw = 0;
	va_list argList;
	va_start( argList, lpszFormat );
    wvsprintf(szMsg, lpszFormat, argList);
	va_end( argList );
    //::lstrcat(szMsg, _T("\n"));
    ::WriteFile(m_hFile, szMsg, lstrlen(szMsg)*sizeof(TCHAR), &dw, 0);

	LeaveCriticalSection(&m_CriticalSection);
}